/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.exporters;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This class is used to manage database connections. It accepts properties of the connection and is able to
 * establish connections to the database
 *  
 *
 * @author Basil Shikin
 *
 */
public class ConnectionManager
{
    private static Log log = LogFactory.getLog( ConnectionManager.class );
    
    public static final String KEY_HOST     = "db.host";
    public static final String KEY_PORT     = "db.port";
    public static final String KEY_DATABASE = "db.database";
    public static final String KEY_USERNAME = "db.username";
    public static final String KEY_PASSWORD = "db.password";

    public enum DatabaseType
    {
        MY_SQL,
        MSSQL,
        ORACLE
    }
    
    private final String       host;
    private final int          port;
    private final String       database;
    private final String       username;
    private final String       password;
    private final DatabaseType databaseType;
    
    private String connectionUrlPrefix    = null;
    private String connectionUrlDelimiter = null;
    
    public ConnectionManager( DatabaseType databaseType, Properties properties )
    {
        if ( properties == null )   throw new IllegalArgumentException("Invalid properties specified");
        if ( databaseType == null ) throw new IllegalArgumentException("Invalid database type specified");
        
        this.databaseType = databaseType;
        
        host = properties.getProperty( KEY_HOST );
        if ( host == null ) throw new IllegalArgumentException("Invalid host specified");
        
        port = Integer.parseInt( properties.getProperty( KEY_PORT, "3306") );
        
        database = properties.getProperty( KEY_DATABASE );
        if ( database == null ) throw new IllegalArgumentException("Invalid database specified");
        
        
        username = properties.getProperty( KEY_USERNAME );
        password = properties.getProperty( KEY_PASSWORD );
    }
    
    public void ensureCanConnect() throws SQLException
    {
        Connection connection = null;
        Statement  statement  = null;
        try
        {
            connection = retrieveConnection();
            statement  = connection.createStatement();
            statement.execute( "SELECT 1" );
            
            log.info("Connection \"" + connection + "\" established");
        }
        finally
        {
            closeStatement( statement );
            closeConnection( connection );
        }
    }
    
    public Connection retrieveConnection() throws SQLException 
    {
        try
        {
            loadDriver();
        
            final String url = connectionUrlPrefix + host + ":" + port + connectionUrlDelimiter + database;
            
            return DriverManager.getConnection(url, username, password) ;
        }
        catch (SQLException e )
        {
            throw e;
        }
        catch ( Exception e )
        {
            throw new SQLException( "Unable to load " + databaseType + " driver", e );
        }
    }
    
    public void closeConnection( Connection connection )
    {
        try
        {
            if ( connection != null ) connection.close();
        }
        catch ( Throwable e )
        {
            log.warn("Unable to close sql connection: " + connection, e );
        }
    }
    
    public void closeStatement( Statement statement)
    {
        try
        {
            if ( statement != null ) statement.close();
        }
        catch ( Throwable e )
        {
            log.warn("Unable to close sql statement: " + statement, e );
        }
    }

    public void closeResult(ResultSet result)
    {
        try
        {
            if ( result != null ) result.close();
        }
        catch ( Throwable e )
        {
            log.warn("Unable to close result set: " + result, e );
        }
    }
    
    private void loadDriver() throws Exception
    {
        try
        {
            if ( databaseType == DatabaseType.MSSQL )
            {
                Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
                
                connectionUrlPrefix = "jdbc:microsoft:sqlserver://";
                connectionUrlDelimiter = "/";
            }
            else if ( databaseType == DatabaseType.MY_SQL )
            {
                Class.forName ("com.mysql.jdbc.Driver").newInstance();
                
                connectionUrlPrefix = "jdbc:mysql://";
                connectionUrlDelimiter = "/";
            }
            else if ( databaseType == DatabaseType.MSSQL )
            {
                Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    
                connectionUrlPrefix =  "jdbc:oracle:oci:@";
                connectionUrlDelimiter = ":";
            }
            else 
            {
                throw new IllegalArgumentException("Unknown database type: " + databaseType );
            }
        }
        catch (Exception e )
        {
            log.error("Unable to load SQL database driver", e );
            
            throw e;
        }
    }
    
    /**
     * Retrieve available database types
     * 
     * @return Types of databases currently supported
     */
    public static Collection<DatabaseType> getSupportedDatabaseTypes()
    {
        return Arrays.asList( DatabaseType.values() );
    }
}
